import express from "express";
import _ from "lodash";

export default (db) => {
  const router = express.Router();

  // 获取所有 POI
  router.get("/", async (req, res) => {
    try {
      await db.read();
      res.json(db.data.pois || []);
    } catch (error) {
      res.status(500).json({ error: "Database read failed" });
    }
  });

  // 搜索 POI
  router.get("/search", async (req, res) => {
    try {
      await db.read();
      const { name, city, type } = req.query;

      let results = db.data.pois || [];

      if (name) {
        results = results.filter((p) =>
          p.name.toLowerCase().includes(name.toLowerCase())
        );
      }

      if (city) {
        results = results.filter((p) =>
          p.city.toLowerCase().includes(city.toLowerCase())
        );
      }

      if (type) {
        results = results.filter(
          (p) => p.type.toLowerCase() === type.toLowerCase()
        );
      }

      res.json(results);
    } catch (error) {
      res.status(500).json({ error: "Search failed" });
    }
  });

  //获取单个POI
  router.get("/:id", async (req, res) => {
    try {
      await db.read();
      const id = req.params.id;

      // 查找对应 ID 的 POI
      const poi = db.data.pois.find((p) => p.id === id);

      if (!poi) {
        return res.status(404).json({ error: "POI not found" });
      }

      res.json(poi);
    } catch (error) {
      res.status(500).json({ error: "Get POI failed" });
    }
  });

  // 创建新 POI
  router.post("/", async (req, res) => {
    try {
      await db.read();

      const newPoi = {
        ...req.body,
        id: Date.now().toString(), // 生成唯一ID
      };

      db.data.pois.push(newPoi);
      await db.write();

      res.status(201).json(newPoi);
    } catch (error) {
      res.status(500).json({ error: "Create failed" });
    }
  });

  // 更新 POI
  router.put("/:id", async (req, res) => {
    try {
      await db.read();
      const id = req.params.id;

      const index = _.findIndex(db.data.pois, { id });
      if (index === -1) {
        return res.status(404).json({ error: "POI not found" });
      }

      // 保留原有ID，更新其他字段
      db.data.pois[index] = {
        ...db.data.pois[index],
        ...req.body,
        id, // 确保ID不变
      };

      await db.write();
      res.json(db.data.pois[index]);
    } catch (error) {
      res.status(500).json({ error: "Update failed" });
    }
  });

  // 删除 POI
  router.delete("/:id", async (req, res) => {
    try {
      await db.read();
      const id = req.params.id;

      const initialLength = db.data.pois.length;
      db.data.pois = db.data.pois.filter((p) => p.id !== id);

      if (db.data.pois.length === initialLength) {
        return res.status(404).json({ error: "POI not found" });
      }

      await db.write();
      res.status(204).end();
    } catch (error) {
      res.status(500).json({ error: "Delete failed" });
    }
  });

  return router;
};
